import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:uuid/uuid.dart';

class SjDeviceUtils {
  static final DeviceInfoPlugin _deviceInfoPlugin = DeviceInfoPlugin();
  static final Uuid _uuid = Uuid();
  static const _uuidKey = 'deviceUUID';
  static const _udidKey = 'deviceUDID';
  static final FlutterSecureStorage _secureStorage = FlutterSecureStorage();

  static Future<String> getSystemVersion() async {
    var deviceInfo = await _deviceInfoPlugin.deviceInfo;
    if (deviceInfo is AndroidDeviceInfo) {
      return deviceInfo.version.release;
    } else if (deviceInfo is IosDeviceInfo) {
      return deviceInfo.systemVersion;
    }
    return "Unknown";
  }

  static Future<String> getPlatform() async {
    if (Platform.isAndroid) {
      return "Android";
    } else if (Platform.isIOS) {
      return "iOS";
    }
    return "Unknown";
  }

  static Future<String> getUuid() async {
    String? storedUUID = await _secureStorage.read(key: _uuidKey);
    if (storedUUID == null) {
      storedUUID = _uuid.v4();
      await _secureStorage.write(key: _uuidKey, value: storedUUID);
    }
    return storedUUID;
  }

  static Future<String?> getUdid() async {
    // return 'C738A65F-F847-48AB-9ABD-AAF5DA8D8E13';
    String? storedUDID = await _secureStorage.read(key: _udidKey);
    if (storedUDID == null) {
      if (Platform.isAndroid) {
        var androidInfo = await _deviceInfoPlugin.androidInfo;
        storedUDID = androidInfo.id;
      } else if (Platform.isIOS) {
        var iosInfo = await _deviceInfoPlugin.iosInfo;
        storedUDID = iosInfo.identifierForVendor;
      }
      await _secureStorage.write(key: _uuidKey, value: storedUDID);
    }
    return storedUDID;
  }

  static Future<String> getDeviceModel() async {
    var deviceInfo = await _deviceInfoPlugin.deviceInfo;
    if (deviceInfo is AndroidDeviceInfo) {
      return deviceInfo.hardware;
    } else if (deviceInfo is IosDeviceInfo) {
      return deviceInfo.model;
    }
    return "Unknown";
  }

  static Future<String> getPackageName() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.packageName;
  }

  static Future<String> getAppVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  static Future<String> getBuildNumber() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.buildNumber;
  }

  static String getSystemLanguage() {
    return Platform.localeName.split('_')[0];
  }
}
